package com.gaojiabao.panghu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaojiabao.panghu.constant.ResultCodeEnum;
import com.gaojiabao.panghu.data.pojo.Admin;
import com.gaojiabao.panghu.mapper.AdminMapper;
import com.gaojiabao.panghu.service.LoginService;
import com.gaojiabao.panghu.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: gaojiabao
 * @Date: 2024/11/3 14:48
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private AdminMapper adminMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //后台登录
    @Override
    @Transactional
    public Result<?> login(Admin admin) {
        if (null == admin ||
                !StringUtils.hasText(admin.getUsername()) ||
                !StringUtils.hasText(admin.getPassword())) {
            return Result.build(null, ResultCodeEnum.LOGIN_PARAM_EMPTY);
        }

        //mybatis-plus查询
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getUsername, admin.getUsername()).eq(Admin::getPassword, admin.getPassword());
        List<Admin> admins = adminMapper.selectList(adminLambdaQueryWrapper);

        if (admins.isEmpty()) {
            return Result.build(null, ResultCodeEnum.LOGIN_ERROR);
        }

        //生成UUID,存储用户登录信息
        String loginUUID = UUID.randomUUID().toString().replace("-", "");
        //构造hash存储的对象
        Map<String, ? extends Serializable> map =
                Map.of("id", admins.get(0).getId(),
                        "username", admins.get(0).getUsername(),
                        "password", admins.get(0).getPassword());
        //存储对象到redis中，设置过期时间
        redisTemplate.opsForHash().putAll(loginUUID, map);
        redisTemplate.expire(loginUUID, 3, TimeUnit.HOURS);

        return Result.ok(Map.of("username", admins.get(0).getUsername(), "loginUUID", loginUUID));
    }
}
